package com.example.demo.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.BackMonkey;
import com.example.demo.entity.BackMonkey2;
import com.example.demo.entity.TargetAndBackMonkey2;
import com.example.demo.form.BackMonkeyForm2;
import com.example.demo.service.BackMonkeyService;
import com.example.demo.service.BackMonkeyService2;
import com.sun.el.parser.ParseException;
@RestController
@RequestMapping(value = "/BackMonkey2")
public class BackMonkeyController2 {
	@Autowired
	private BackMonkeyService service1;
	@Autowired
	private BackMonkeyService2 service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(value = "/save")
	private Object save(BackMonkeyForm2 Form) throws java.text.ParseException {
		Integer saleId1 = Form.getId();
		Date d= new Date();
		Date d1 = dateFormat1.parse("1999-01-01");
		BackMonkey sale1= new BackMonkey();
		BackMonkey Sale1= new BackMonkey();
		BackMonkey2 sale2= new BackMonkey2();
		BackMonkey2 Sale2= new BackMonkey2();
		if(saleId1==null) {
			Sale1.setMonth(Form.getMonth());
			Sale1.setYears(Form.getYears());
			sale1 = service1.save(Sale1);
		}else {
			 sale1 = service1.findById(saleId1);
			 sale1.setMonth(Form.getMonth());
			 sale1.setYears(Form.getYears());
			 service1.save(sale1);
				List<BackMonkey2> list = service2.findByBackmonkey(sale1);
				for (BackMonkey2 BackMonkey2 : list) {
					if(d1.compareTo(BackMonkey2.getBeginDate())==-1) {
						d1=BackMonkey2.getBeginDate();
						Sale2=BackMonkey2;
					}
				}
				Sale2.setEndDate(d);
				service2.save(Sale2);
				
		}
		BeanUtils.copyProperties(Form, sale2, "id");
		sale2.setBackmonkey(sale1);
		sale2.setBeginDate(d);
		service2.save(sale2);
		return new AjaxResult("数据保存成功");			
	}
	
	@RequestMapping(value = "/findbydate")
	public Object findbyId(BackMonkeyForm2 form) throws ParseException, java.text.ParseException {
		Integer month = form.getMonth();
		Integer years = form.getYears();
		BackMonkey t1 = service1.findByMonthAndYears(month, years);
		List<BackMonkey2> list=service2.findByBackmonkeyId(t1.getId());
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Date d = dateFormat1.parse("1999-01-01");
		BackMonkey2 yan=new BackMonkey2();
		for(BackMonkey2 y :list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				yan=y;
			}
		}
		return new AjaxResult(yan);
	}
	
}
